package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Prop;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import io.renren.annotation.Login;
import io.renren.annotation.LoginUser;
import io.renren.common.utils.R;
import io.renren.entity.StudentEntity;
import io.renren.service.StudentService;
import io.renren.util.ApiBaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static io.renren.util.CommonUtil.getProp;

/***
 * API登录授权
 * @author 霍礼康
 */
@RestController
@RequestMapping("/api/auth")
public class ApiAuthController extends ApiBaseAction {
    static Prop prop = getProp();
    @Autowired
    private StudentService studentService;

    /***
     * 授权 把openid存到student表中
     * @param student 学员
     * @param code 用code获取openid
     * @param state
     * @return
     */
    @Login
    @RequestMapping("oauth")
    public R oauth(@LoginUser StudentEntity student, String code, String state) {
        //用户同意授权，获取code
        if (code != null) {
            String appId = prop.get("appId");
            String secret = prop.get("appSecret");
            //通过code换取网页授权access_token
            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
            String token = snsAccessToken.getAccessToken();
            String openId = snsAccessToken.getOpenid();
            //拉取用户信息(需scope为 snsapi_userinfo)
            ApiResult apiResult = SnsApi.getUserInfo(token, openId);
            if (apiResult.isSucceed()) {
                JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
                student.setOpenid(openId);
                studentService.updateById(student);
            } else {
                return R.fail("授权失败");
            }
        } else {
            return R.fail("code is null");
        }
        return R.ok();
    }


}
